/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.workcell.workdata.im.mvc.interceptor;

import com.workcell.workdata.im.annotation.AccessToken;
import com.workcell.workdata.im.annotation.ClientOrigin;
import com.workcell.workdata.im.annotation.GreenFunction;
import com.workcell.workdata.im.annotation.UID;
import com.workcell.workdata.im.component.holder.UidHolder;
import com.workcell.workdata.im.constant.Common;
import com.workcell.workdata.im.model.app.Origin;
import com.workcell.workdata.im.model.response.ResponseEntity;
import com.workcell.workdata.im.service.AccessTokenService;
import com.workcell.workdata.im.util.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 来自客户端的接口请求拦截器，验证token
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

	@Resource
	private AccessTokenService accessTokenService;

	private static final String TAG = "ATTR-THREAD-NAME";


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

		if (!(handler instanceof HandlerMethod)){
			response.setStatus(HttpStatus.NOT_FOUND.value());
			return false;
		}

		if (((HandlerMethod)handler).hasMethodAnnotation(GreenFunction.class)){
			return true;
		}

		Origin origin = (Origin) request.getAttribute(ClientOrigin.class.getName());

		String token = request.getHeader(Common.MVC_HEADER_TOKEN);

		Long uid = accessTokenService.getUid(origin,token);

		/*
		 * 直接拒绝无token的接口调用请求或者token没有查询到对应的登录用户
		 */
		if (uid == null) {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			response.getWriter().println(JSON.toJSONString(ResponseEntity.make(HttpStatus.UNAUTHORIZED)));
			return false;
		}

		request.setAttribute(UID.class.getName(), uid);
		request.setAttribute(AccessToken.class.getName(), token);

		UidHolder.setUid(uid);

		request.setAttribute(TAG,Thread.currentThread().getName());

		Thread.currentThread().setName("http-uid-" + uid);

		return true;

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {

		UidHolder.remove();

		Object initialName = request.getAttribute(TAG);

		String currName = Thread.currentThread().getName();

		if (initialName != null && !Objects.equals(initialName,currName)){
			Thread.currentThread().setName(initialName.toString());
		}
	}
}
